package com.flink.examples.functions;

import com.flink.examples.DataSource;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.api.java.tuple.Tuple4;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.List;

/**
 * @Description SideOutput方法：（侧输出）从主数据流中根据outputTag获取额外的输出流（分流场景下使用）
 * @Author JL
 * @Date 2020/09/17
 * @Version V1.0
 */
public class SideOutput {

    /**
     * 参考示例：https://blog.csdn.net/jerome520zl/article/details/103963549
     */

    /**
     * 遍历集合，将数据流切分成多个流并打印
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        List<Tuple3<String, String, Integer>> tuple3List = DataSource.getTuple3ToList();
        //Datastream
        DataStream<Tuple3<String, String, Integer>> dataStream = env.fromCollection(tuple3List);
        //自定义man和girl两个性别tag
        OutputTag<Tuple4<String, String, Integer, String>> manTag = new OutputTag<Tuple4<String, String, Integer, String>>("man"){};
        OutputTag<Tuple4<String, String, Integer, String>> girlTag = new OutputTag<Tuple4<String, String, Integer, String>>("girl"){};
        //将所有流数据输入到process做处理
        SingleOutputStreamOperator<Tuple4<String, String, Integer, String>> output = dataStream.process(new ProcessFunction<Tuple3<String,String,Integer>, Tuple4<String, String, Integer, String>>() {
            @Override
            public void processElement(Tuple3<String, String, Integer> value, Context ctx, Collector<Tuple4<String, String, Integer, String>> out) throws Exception {
                //将数据流按不同的性别划分，创建新的Tuple4，分别绑定到不同性别的tag
                if (value.f1.equals("man")){
                    ctx.output(manTag, Tuple4.of(value.f0, value.f1, value.f2, "男"));
                }else {
                    ctx.output(girlTag, Tuple4.of(value.f0, value.f1, value.f2, "女"));
                }
            }
        });
        //获取指定tag的数据流
        DataStream<Tuple4<String, String, Integer, String>> dataStream1 = output.getSideOutput(manTag);
        DataStream<Tuple4<String, String, Integer, String>> dataStream2 = output.getSideOutput(girlTag);
        //打印
        dataStream1.print();
        dataStream2.print();
        env.execute("flink Split job");
    }
}
/*
(张三,man,20,男)
(李四,girl,24,女)
(王五,man,29,男)
(刘六,girl,32,女)
(伍七,girl,18,女)
(吴八,man,30,男)
 */